from sqlalchemy.orm import Session
from core.response import resp_500
from core.logger import logger
from app.monitor_metrics.models.prom_alarm_record import PromAlarmRecord

class PromAlarmRecordHandler():
    """  PromAlarmRecord Handler
    """
    def __init__(self):
        pass


    def get_alarm_record_search(self, db: Session, page: int, per_page: int, field: str, value: str):
        try:
            field_info = {field: value}
            order_info = {"status": "asc", "update_at": "desc"}
            result = PromAlarmRecord.filter_by_field_search(db, page, per_page, field_info, order_info)
            if not result:
                logger.warning(f"get alarm record search, result is null => {field}:{value}")
                return False, None

        except Exception as e:
            message = f"get alarm record search by {field}:{value} error"
            logger.exception(f"{message} => {e}")
            return resp_500(message)

        return True, result


    def get_alarm_record_match(self, db: Session, page: int, per_page: int, field: str, value: str):
        try:
            result = PromAlarmRecord.filter_by_field_match(db, page, per_page, {field: value})
            if not result:
                logger.warning(f"get alarm record match, result is null => {field}:{value}")
                return False, None

        except Exception as e:
            message = f"get alarm record match by {field}:{value} error"
            logger.exception(f"{message} => {e}")
            return resp_500(message)

        return True, result




    def get_prom_alarm_record_block_global(self, db: Session):
        try:
            block_global_info = PromAlarmRecord.get_object_info_for_block_global(db)
            if not block_global_info:
                # 不存在，这创建
                data = {
                    "name": "BlockGlobalAlarm",
                    "classes": "prometheus",
                    "status": "resolved",
                    "target": "屏蔽全局告警",
                    "state": 1,
                    "number": 1,
                    "fingerprint": "bYpQWnTVDSXQgLIL"
                }
                
                result = PromAlarmRecord.add(db, data)
                if not result:
                    logger.warning(f"add alarm record block global failed")
                    return False, None
                block_global_info = data
                block_global_info["uuid"] = result.uuid
        except Exception as e:
            message = f"get alarm record block global error"
            logger.exception(f"{message} => {e}")
            return resp_500(message)

        return True, block_global_info


    #
    # def add_alarm_record(self, db: Session, data: dict):
    #     try:
    #         alarm_record_object = PromAlarmRecord.get_object(db, data["name"], data["fingerprint"])
    #         if alarm_record_object:
    #             # 如果存在， 则异常返回
    #             logger.error(f"add alarm record failed,{data['name']}:{data['fingerprint']} was exist")
    #             return False
    #
    #         PromAlarmRecord.add(db, data)
    #     except Exception as e:
    #         message = f"add alarm record error"
    #         logger.exception(f"{message} => {e}")
    #         return resp_500(message)
    #
    #     return True



    def update_alarm_record(self, db: Session, data: dict):
        """
        修改告警记录信息
        """
        try:
            alarm_record_object = PromAlarmRecord.get_object_by_uuid(db, data["uuid"])
            if not alarm_record_object:
                # 如果存在， 则异常返回
                logger.error(f"update alarm record failed, uuid:{data['uuid']} was not exist")
                return False

            # 更新告警指标
            result = PromAlarmRecord.update(db, data)
            if not result:
                logger.error(f"update alarm record to database failed")
                return False
        except Exception as e:
            message = f"update alarm record error "
            logger.exception(f"{message} => {e}")
            return resp_500(message)

        return True



    def delete_alarm_record(self, db: Session, data: dict):
        """
        删除告警记录信息
        """
        try:
            alarm_record_object = PromAlarmRecord.get_object_by_uuid(db, data["uuid"])
            if not alarm_record_object:
                # 如果存在， 则异常返回
                logger.error(f"delete alarm record failed, uuid:{data['uuid']} was not exist")
                return False

            # 删除告警指标
            PromAlarmRecord.delete_object_by_uuid(db, data['uuid'])
        except Exception as e:
            message = f"delete alarm record error"
            logger.exception(f"{message} data:{data} => {e}")
            return resp_500(message)

        return True






